// 用于定时向父窗口 post 页面高度的通用 composable
import { onMounted, onUnmounted } from "vue";

/**
 * 自动定时向父窗口 post 页面高度
 * @param {string} id 页面唯一标识
 * @param {number} intervalMs 间隔毫秒，默认1000
 */
export function useAutoPostHeight(id, intervalMs = 1000) {
  let postMessageTimer = null;

  onMounted(() => {
    postMessageTimer = setInterval(() => {
      if (
        typeof window !== "undefined" &&
        window.parent &&
        window.parent !== window &&
        typeof window.parent.postMessage === "function"
      ) {
        window.parent.postMessage(
          { type: "resize", id, height: document.body.scrollHeight },
          "*"
        );
      }
    }, intervalMs);
  });

  onUnmounted(() => {
    if (postMessageTimer) {
      clearInterval(postMessageTimer);
      postMessageTimer = null;
    }
  });
}
